package com.book.service.impl;

import com.book.dao.AddressMapper;
import com.book.dao.UserMapper;
import com.book.pojo.Address;
import com.book.pojo.User;
import com.book.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService  {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AddressMapper addressMapper;

    /**
     * 添加组合1对多  因为插入多次, 控制事务
     * @param user
     * @return
     */
    @Override
    //事务
    public Integer add(User user) {

        //插入1
        userMapper.add( user );
        for (Address address : user.getAddressList()) {
            //设置1的id
            address.setUserId( user.getId() );
            //插入当前多中的1
            addressMapper.add( address );
        }
        return 1;
    }

    @Override
    public List<Address> findAllAddress() {
        return addressMapper.findAll();
    }

    @Override
    public List<Address> findByUserId(Integer userId) {

        return addressMapper.findByUserId( userId );
    }

    @Override
    public Integer addList(List<User> userList) {
        for (User user : userList) {
            //插入1
            userMapper.add( user );
            for (Address address : user.getAddressList()) {
                //设置1的id
                address.setUserId( user.getId() );
                //插入当前多中的1
                addressMapper.add( address );
            }
        }
        return userList.size();
    }

    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }
}
